import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 导入登录注册组件
const Reg = () => import('@/views/Reg/Reg.vue')
const Login = () => import('@/views/Login/Login.vue')
const Main = () => import('@/views/Main/Main.vue')
const Home = () => import('@/views/Menus/Home/Home.vue')
const UserInfo = () => import('@/views/Menus/User/UserInfo.vue')
const UserAvatar = () => import('@/views/Menus/User/UserAvatar.vue')
const UserPwd = () => import('@/views/Menus/User/UserPwd.vue')
const ArtCate = () => import('@/views/Menus/Article/ArtCate.vue')
const ArtList = () => import('@/views/Menus/Article/ArtList.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

// 声明路由规则
const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  // 后台主页的路由规则
  {
    path: '/',
    component: Main,
    // 开启路由重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home
      },
      // 用户信息的子路由规则
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 使用导航守卫,进行未登录的权限控制
// to：到哪里去
// from:从哪里来
// next:是否放行,函数
router.beforeEach((to, from, next) => {
  // 在特定的条件下跳转至 /login
  // 条件1:未登录,没有 token
  // 条件2:要去的页面不是 /login 和 /reg
  //
  // 白名单:不管登没登录都可以访问的页面
  const whiteList = ['/login', '/reg']
  // if (!store.state.user.token && to.path !== '/login' && to.path !== '/reg') {
  if (!store.state.user.token && !whiteList.includes(to.path)) {
    return next('/login')
  }
  next()
})
export default router
